﻿using System;
using System.Xml;
using System.Web;

namespace Landscape
{
    class DocumentTemplate : Template
    {
        public bool IsMaster;
        public string WrapperName;
        public bool OmitXmlDeclaration;

        public DocumentTemplate(string xmlTemplatePath) : base(xmlTemplatePath)
        {
            XmlNode rootTemplateNode = null;
            XmlNodeList xsltTemplates = TemplateDom.GetElementsByTagName("template", Context.xslNamespace);
            if (xsltTemplates.Count > 0)
            {
                foreach (XmlNode tplNode in xsltTemplates)
                {
                    XmlNode matchAttr = tplNode.Attributes.GetNamedItem("match");
                    XmlNode wrapperAttr = tplNode.Attributes.GetNamedItem("wrapper", Context.lscNamespace);

                    if (matchAttr != null && matchAttr.Value.Equals("/"))
                    {
                        rootTemplateNode = tplNode;
                        if (wrapperAttr != null && !string.IsNullOrEmpty(wrapperAttr.Value))
                        {
                            WrapperName = wrapperAttr.Value;

                            rootTemplateNode.Attributes.RemoveNamedItem("wrapper", Context.lscNamespace);
                            break;
                        }
                    }
                }
            }

            if (rootTemplateNode == null)
            {
                throw new Exception("Template does not contain a root template (<xsl:template match=\"/\"> ... </xsl:template>)");
            }

            IsMaster = string.IsNullOrEmpty(WrapperName);
            OutputSettings = new TemplateOutputSettings() {
                Encoding = "utf-8",
                Indent = Context.outputIndent,
                OmitXmlDeclaration = true,
                Standalone = false
            };
            if (IsMaster)
            {
                OutputSettings.Method = Context.xslOutputMethod;
                OutputSettings.DocTypePublic = Context.outputDocTypePublic;
                OutputSettings.DocTypeSystem = Context.outputDocTypeSystem;
                ConfigureOutput(false);
            }
            else
            {
                OutputMethod = OutputMethods.xml;
                ConfigureOutput(true);
            }

            // create compiled transform object
            TemplateCompiledTransform = Context.Instance.compiler.Compile(TemplateDom);
        }
    }
}
